import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../../environments/environment';

@Component({
  selector: 'app-workflow-viewer',
  templateUrl: './workflow-viewer.component.html',
  styleUrls: ['./workflow-viewer.component.scss']
})
export class WorkflowViewerComponent implements OnInit {
  apiBaseUrl = environment.apiUrl.replace('/api', '');
  isLoading = true;
  errorMessage = '';
  workflows: any[] = [];
  workflowInstances: any[] = [];
  elsaStatus: any = null;

  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    this.loadWorkflows();
    this.loadWorkflowInstances();
    this.isLoading = false;
  }

  private checkElsaStatus(): void {
    // Skip status check for now and just load workflows directly
    this.loadWorkflows();
    this.loadWorkflowInstances();
    this.isLoading = false;
  }

  private loadWorkflows(): void {
    this.http.get(`${environment.apiUrl}/workflow-definitions`).subscribe({
      next: (response: any) => {
        this.workflows = response.items || [];
      },
      error: (error) => {
        console.error('Failed to load workflows:', error);
      }
    });
  }

  private loadWorkflowInstances(): void {
    this.http.get(`${environment.apiUrl}/workflow-instances`).subscribe({
      next: (response: any) => {
        this.workflowInstances = response.items || [];
      },
      error: (error) => {
        console.error('Failed to load workflow instances:', error);
      }
    });
  }

  retryConnection(): void {
    this.isLoading = true;
    this.errorMessage = '';
    this.elsaStatus = null;
    this.workflows = [];
    this.workflowInstances = [];
    this.checkElsaStatus();
  }

  executeWorkflow(workflowId: string): void {
    const request = {
      definitionId: workflowId,
      versionOptions: { IsLatest: true }
    };

    this.http.post(`${environment.apiUrl}/workflow-instances`, request).subscribe({
      next: (response) => {
        console.log('Workflow executed:', response);
        this.loadWorkflowInstances(); // 刷新实例列表
      },
      error: (error) => {
        console.error('Failed to execute workflow:', error);
      }
    });
  }

  refreshData(): void {
    this.loadWorkflows();
    this.loadWorkflowInstances();
  }
} 